// state/music.dart
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:audio_session/audio_session.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';

class MusicState with ChangeNotifier {
  final AudioPlayer audioPlayer = AudioPlayer();
  List<Map<String, String>> playlist = [];
  Map<String, String>? currentSong;
  int type = 1;
  bool isPlaying = false;

  MusicState() {
    // 调用异步初始化方法
    _initialize();
  }

  Future<void> _initialize() async {
    // 设置音频会话以允许后台播放
    await AudioSession.instance.then((session) async {
      await session.configure(AudioSessionConfiguration.music());
    });

    audioPlayer.setReleaseMode(ReleaseMode.stop);

    // 监听播放完成事件
    audioPlayer.onPlayerComplete.listen((_) {
      nextSong(); // 播放下一首
    });

    // 监听播放状态变化
    audioPlayer.onPlayerStateChanged.listen((state) {
      if (state == PlayerState.stopped) {
        isPlaying = false;
        notifyListeners();
      }
    });
  }

  void stopForegroundTask() async {
    await FlutterForegroundTask.stopService();
  }

  void setType(int newtype) {
    type = newtype;
    notifyListeners();
  }

  void setPlaylist(List<Map<String, String>> newPlaylist) {
    playlist = newPlaylist;
    notifyListeners();
  }

  void setCurrentSong(Map<String, String>? song) {
    if (song == null) return;
    // 延迟执行通知监听器的逻辑
    WidgetsBinding.instance.addPostFrameCallback((_) {
      currentSong = song;
      notifyListeners();
    });
  }

  void playSong(Map<String, String> song) async {
    print(01236548888);
    setCurrentSong(song);
    print(song['audio_url']);
    if(song['audio_url']==null){
      return;
    }
    try {
      await audioPlayer.play(UrlSource(song['audio_url']!));
    isPlaying = true;
    notifyListeners();
    } catch (e) {
      print(e);
    }
    
  }

  void pauseSong() async {
    await audioPlayer.pause();
    isPlaying = false;
    notifyListeners();
  }

  void resumeSong() async {
    await audioPlayer.resume();
    isPlaying = true;
    notifyListeners();
  }

  void stopSong() {
    audioPlayer.stop();
    isPlaying = false;
    notifyListeners();
  }

  void seekToPosition(Duration newPos) async {
    await audioPlayer.seek(newPos);
  }

  int findIndexById() {
    if (currentSong == null) return -1;

    int currentIndex =
          playlist.indexWhere((song) => song['id'] == currentSong!['id']);

    return currentIndex;
  }

  void deleteCurrentSong() async {
    // 检查是否有当前歌曲
    if (currentSong != null) {
      // 获取当前歌曲在播放列表中的索引
      int currentIndex =
          playlist.indexWhere((song) => song['id'] == currentSong!['id']);

      // 如果找到了当前歌曲
      if (currentIndex != -1) {
        // 从播放列表中移除当前歌曲
        playlist.removeAt(currentIndex);

        // 停止当前正在播放的歌曲
        if (isPlaying) {
          stopSong();
        }

        // 根据删除的位置来设置新的 currentSong
        if (playlist.isNotEmpty) {
          // 如果不是最后一个元素，选择下一个元素
          if (currentIndex < playlist.length) {
            setCurrentSong(playlist[currentIndex]);
          } else {
            // 如果是最后一个元素，选择第一个元素
            setCurrentSong(playlist[0]);
          }
        } else {
          // 如果播放列表为空，清空 currentSong
          setCurrentSong(null);
        }
      }
    }
  }
  void nextSong() {
    final playlist = this.playlist;
    final currentSongIndex = findIndexById();

    if (playlist.isNotEmpty) {
      final nextIndex = (currentSongIndex + 1) % playlist.length;
      final nextSong = playlist[nextIndex];
      playSong(nextSong);
    }
  }
}
